package com.sky.service.impl;

import com.sky.dto.SetmealDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 套餐业务实现
 */
@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        return setmealMapper.list(setmeal);
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }

    @Override
    public void add(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        Setmeal exists = setmealMapper.checkExists(setmeal);
        if (exists != null) {
            // 已经存在套餐，不允许重复添加
            throw new RuntimeException("已经存在套餐，不允许重复添加");
        }

        setmealMapper.add(setmeal);
        addSetmealDish(setmealDTO, setmeal);
    }

    @Override
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.update(setmeal);
        setmealDTO.getSetmealDishes().forEach(dish -> dish.setSetmealId(setmeal.getId()));
        setmealDishMapper.deleteBatch(setmealDTO.getSetmealDishes());
        addSetmealDish(setmealDTO, setmeal);
    }

    @Override
    public void startOrStop(Integer status, Integer id) {
        setmealMapper.startOrStop(status, id);
    }

    @Override
    public void delete(Long id) {
        setmealMapper.delete(id);
        setmealDishMapper.deleBySetmealId(id);
    }

    private void addSetmealDish(SetmealDTO setmealDTO, Setmeal setmeal) {
        for (SetmealDish setmealDish : setmealDTO.getSetmealDishes()) {
            Dish byId = dishMapper.getById(setmealDish.getDishId());
            setmealDish.setName(byId.getName());
            setmealDish.setPrice(byId.getPrice());
            setmealDish.setSetmealId(setmeal.getId());
        }
        setmealDishMapper.insertBatch(setmealDTO.getSetmealDishes());
    }
}
